/*
 *   Copyright (C) 2006-2010 Jiri Majer. All Rights Reserved.
 *   DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 *   This code is free software; you can redistribute it and/or modify it
 *   under the terms of the GNU General Public License version 2 only, as
 *   published by the Free Software Foundation.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.diabetesdiary.commons.swing.calendar;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;

/**
 *
 * @author Jirka Majer
 */
public class CalendarPanel extends javax.swing.JPanel {

    public CalendarPanel(LocalDate ldate, Locale locale) {
        this.date = ldate;
        this.locale = locale;
        model = new DayTableModel(date);
        initComponents();
        jTable1.setDefaultRenderer(LocalDate.class, new LocalDateRenderer());
        for (int i = 0; i < jTable1.getColumnCount(); i++) {
            TableColumn col = jTable1.getColumnModel().getColumn(i);
            col.setHeaderValue(date.withDayOfWeek(i + 1).toString("E", this.locale));
        }
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable1.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                int row = jTable1.rowAtPoint(e.getPoint());
                int column = jTable1.columnAtPoint(e.getPoint());
                LocalDate clickDate = (LocalDate) jTable1.getValueAt(row, column);
                setLocalDate(clickDate);
                onDayClicked(clickDate);
            }
        });

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new BasicArrowButton(BasicArrowButton.WEST);
        jButton2 = new BasicArrowButton(BasicArrowButton.EAST);
        jComboBox1 = new javax.swing.JComboBox();
        yearSpinner = new YearSpinner(date.toDateTimeAtCurrentTime());

        jTable1.setModel(model);
        jTable1.setCellSelectionEnabled(true);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("<"); // NOI18N
        jButton1.setPreferredSize(new java.awt.Dimension(20, 20));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(">"); // NOI18N
        jButton2.setPreferredSize(new java.awt.Dimension(20, 20));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new DefaultComboBoxModel(new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12}));
        jComboBox1.setPreferredSize(new java.awt.Dimension(100, 20));
        jComboBox1.setRenderer(new MonthRenderer(locale));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        yearSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                yearSpinnerStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox1, 0, 101, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(yearSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(yearSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        date = date.plusMonths(1);
        refresh();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        date = date.minusMonths(1);
        refresh();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        date = date.withMonthOfYear((Integer) jComboBox1.getSelectedItem());
        refresh();
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void yearSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_yearSpinnerStateChanged
        YearSpinner spin = (YearSpinner) yearSpinner;
        date = date.withYear(spin.getDateTime().getYear());
        refresh();
    }//GEN-LAST:event_yearSpinnerStateChanged

    private void refresh() {
        model.setLocalDate(date);
        jComboBox1.setSelectedItem(date.getMonthOfYear());
        YearSpinner spin = (YearSpinner) yearSpinner;
        spin.setDateTime(date.toDateTimeAtCurrentTime());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame fr = new JFrame();
                fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                fr.add(new CalendarPanel(new LocalDate(), Locale.getDefault()));
                fr.pack();
                fr.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JSpinner yearSpinner;
    // End of variables declaration//GEN-END:variables
    private DayTableModel model;
    private LocalDate date;
    private Locale locale;

    public void setLocalDate(LocalDate date) {
        this.date = date;
        refresh();
    }

    public void onDayClicked(LocalDate date) {
        System.out.println(date);
    }

    private class LocalDateRenderer implements TableCellRenderer {

        JLabel label = new JLabel();

        public LocalDateRenderer() {
            label.setOpaque(true);
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setBackground(Color.WHITE);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            LocalDate val = (LocalDate) value;
            label.setText(String.valueOf(val.getDayOfMonth()));
            if (val.monthOfYear().equals(date.monthOfYear())) {
                label.setEnabled(true);
                label.setFont(label.getFont().deriveFont(Font.BOLD));
            } else {
                label.setEnabled(false);                
                label.setFont(label.getFont().deriveFont(Font.PLAIN));
            }

            if (isSelected) {
                label.setBackground(table.getSelectionBackground());
                label.setForeground(table.getSelectionForeground());
            } else {
                label.setBackground(table.getBackground());
                label.setForeground(table.getForeground());
            }
            return label;
        }
    }

    private static class MonthRenderer extends JLabel implements ListCellRenderer {

        private Locale locale;

        public MonthRenderer(Locale locale) {
            setOpaque(true);
            setHorizontalAlignment(LEFT);
            setVerticalAlignment(CENTER);
            this.locale = locale;
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            Integer val = (Integer) value;
            setText(new LocalDate().withMonthOfYear(val).toString("MMMM", locale));
            return this;
        }
    }

    private static class DayTableModel extends AbstractTableModel {

        private LocalDate date;

        public DayTableModel(LocalDate date) {
            this.date = date;
        }

        public void setLocalDate(LocalDate date) {
            this.date = date;
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            return 6;
        }

        @Override
        public int getColumnCount() {
            return 7;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            int firstDayOfWeek = date.dayOfMonth().withMinimumValue().getDayOfWeek();
            if (firstDayOfWeek == DateTimeConstants.MONDAY) {
                return date.dayOfMonth().withMinimumValue().minusDays(firstDayOfWeek - 1).plusDays((rowIndex - 1) * 7 + columnIndex);
            }
            return date.dayOfMonth().withMinimumValue().minusDays(firstDayOfWeek - 1).plusDays(rowIndex * 7 + columnIndex);
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return LocalDate.class;
        }
    };
}
